package com.jd.lme.example.parallel;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.function.LongUnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

public class ParallelPrime {
    static final int COUNT = 100_100;

    public static boolean isPrime(long n) {
        return rangeClosed(2, (long)Math.sqrt(n)).noneMatch(i -> n % i == 0);
    }


    private static LongStream rangeClosed(long startInclusive, long endExclusive) {
        return LongStream.rangeClosed(startInclusive, endExclusive);
    }

    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();
        List<String> primes = iterate(2, i -> i +1)
                .parallel()
                .filter(ParallelPrime::isPrime)
                .limit(COUNT)
                .mapToObj(Long::toString)
                .collect(Collectors.toList());
        long end = System.currentTimeMillis();
        System.out.println("Using: " + (end - start) + "ms");
        Files.write(Paths.get("primes.txt"), primes, StandardOpenOption.CREATE);
    }


    private static LongStream iterate(long seed, LongUnaryOperator longUnaryOperator) {
        return LongStream.iterate(seed, longUnaryOperator);
    }

}
